//
//  YLProductDetailController.m
//  YLFinanceService
//
//  Created by she1323 on 2017/8/28.
//  Copyright © 2017年 she1323. All rights reserved.
//  产品详情

#import "YLProductDetailController.h"
#import "YLProductDetailHeader.h"
#import "YLGlobeHeader.h"
#import <Masonry.h>
#import "YLProductDetailViewModel.h"
#import "YLProductAmount0fMoneyCell.h"
#import "YLProductInvestmentTableViewCell.h"
#import "YLSubTitleTableViewCell.h"
#import "YLProductBuyingCycleCell.h"
#import "YLTitleArrowNoSubCell.h"
#import "YLCollectionCalculatorController.h"
#import "YLRelevantAgreementViewController.h"
#import "YLProductModel.h"
#import "YLWebViewController.h"
#import "YLProductIntroductionViewController.h"
#import "PXAlertView.h"
#import "YLAccountTool.h"
#import "YLCertifiedPaymentViewController.h"
#import "YLInvestmentUsefulController.h"
#import "WHProgressHUD.h"
@interface YLProductDetailController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) YLProductDetailViewModel *viewModel;
@property (nonatomic, weak) YLProductDetailHeader *header;
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, weak) UIButton *buyButton;

@property (nonatomic, assign) NSInteger index;
@end

@implementation YLProductDetailController

- (YLProductDetailViewModel *)viewModel
{
    if (!_viewModel) {
        _viewModel = [[YLProductDetailViewModel alloc] init];
    }
    return _viewModel;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];


    if (_index == 1) {
                [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
                self.navigationController.navigationBar.hidden = YES;
        _index ++;
    }
    

    
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
    CGFloat offsetY = self.tableView.contentOffset.y;
    self.navigationController.navigationBar.subviews.firstObject.alpha =  offsetY / (YLScreenW * 900 / 1500.0 - offsetY);
    
    __weak typeof(self) weakSelf = self;
    [_tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.right.left.mas_equalTo(weakSelf.view);
        make.top.mas_equalTo(weakSelf.view).mas_offset(-44 - [UIApplication sharedApplication].statusBarFrame.size.height);
        if (@available(iOS 11.0, *)) {
            make.bottom.mas_equalTo(weakSelf.view.mas_safeAreaLayoutGuideBottom).mas_offset(-44);
        } else {
            make.bottom.mas_equalTo(weakSelf.view).mas_offset(-44);
        }
            }];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setShadowImage:nil];
    self.navigationController.navigationBar.subviews.firstObject.alpha = 1;
    self.navigationController.navigationBar.hidden = NO;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    _index = 1;
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    self.navigationController.navigationBar.hidden = YES;
    
    YLProductDetailHeader *header = [[YLProductDetailHeader alloc] initWithFrame:CGRectMake(0, 0, YLScreenW, YLScreenW * 920 / 1500.0 + 10 + (YLOffsetY - 64))];
    _header = header;
    __weak typeof(self) weakSelf = self;
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:tableView];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tableHeaderView = header;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.right.left.mas_equalTo(weakSelf.view);
        if (@available(iOS 11.0, *)) {
    make.bottom.mas_equalTo(weakSelf.view.mas_safeAreaLayoutGuideBottom).mas_offset(-44);
        } else {
            make.bottom.mas_equalTo(weakSelf.view).mas_offset(-44);
        }

    }];
    
    if (@available(iOS 11.0, *)) {
        tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView = tableView;
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YLProductAmount0fMoneyCell
                                                                   class]) bundle:nil] forCellReuseIdentifier:[YLProductAmount0fMoneyCell cellID]];
    
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YLProductInvestmentTableViewCell class]) bundle:nil] forCellReuseIdentifier:[YLProductInvestmentTableViewCell cellID]];
    
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YLSubTitleTableViewCell class]) bundle:nil] forCellReuseIdentifier:[YLSubTitleTableViewCell cellID]];
    
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YLProductBuyingCycleCell class]) bundle:nil] forCellReuseIdentifier:[YLProductBuyingCycleCell cellID]];
    
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YLTitleArrowNoSubCell class]) bundle:nil] forCellReuseIdentifier:[YLTitleArrowNoSubCell cellID]];
    
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    _buyButton = button;
    button.backgroundColor = YLMainColor;
    [button setTitle:@"正在查询预约状态..." forState:UIControlStateNormal];
    button.userInteractionEnabled = NO;
    [button addTarget:self action:@selector(buyButton:) forControlEvents:UIControlEventTouchUpInside];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        
        if (@available(iOS 11.0, *)) {
        make.bottom.mas_equalTo(weakSelf.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.mas_equalTo(weakSelf.view);
        }
        
        
        make.left.right.mas_equalTo(weakSelf.view);
        make.top.mas_equalTo(tableView.mas_bottom);
    }];
    
    [[self.viewModel.requestCommand execute:_model.productCode] subscribeNext:^(id  _Nullable x) {
        header.headerModel = weakSelf.viewModel.headerModel;
        weakSelf.title =  weakSelf.viewModel.model.productName;
        [weakSelf appointmentStatus:weakSelf.viewModel.model.isReservation];
        [tableView reloadData];
    }];
    
    // 产品介绍
    [self.viewModel.productIntroductionSubject subscribeNext:^(id  _Nullable x) {
        
        if (self.viewModel.model) {
            YLProductIntroductionViewController *productIntroduction = [[YLProductIntroductionViewController alloc] init];
            productIntroduction.productCode = weakSelf.viewModel.model.productCode;
            [weakSelf.navigationController pushViewController:productIntroduction animated:YES];
        }
        
    }];
    
    // 相关协议
    [self.viewModel.relevantAgreementSubject subscribeNext:^(id  _Nullable x) {
        if (weakSelf.viewModel.model) {
            YLRelevantAgreementViewController *relevantAgreement = [[YLRelevantAgreementViewController alloc] init];
            relevantAgreement.productCode = weakSelf.viewModel.model.productCode;
            [weakSelf.navigationController pushViewController:relevantAgreement animated:YES];
        }
        
    }];
    
    [self.viewModel.collectionCalculatorSubject subscribeNext:^(id  _Nullable x) {
        if (self.viewModel.model) {
            YLCollectionCalculatorController *collectionCalculator = [[YLCollectionCalculatorController alloc] init];
            collectionCalculator.model = weakSelf.viewModel.model;
            [weakSelf.navigationController pushViewController:collectionCalculator animated:YES];
        }
        
    }];
    
}

- (void)buyButton:(UIButton *)sender
{
    
    __weak typeof(self) weakSelf = self;
    YLAccount *account = [YLAccountTool account];
    if (account.authState == 0) {
        YLCertifiedPaymentViewController *con = [[YLCertifiedPaymentViewController alloc] init];
        [weakSelf.navigationController pushViewController:con animated:YES];
        return ;
    }
    
    
//    if (self.viewModel.model.indexLimit < self.viewModel.model.leastMoney) {
//     UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"对不起,您的预约额度小于起投金额" preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {}];
//        [alertController addAction:okAction];
//        [self presentViewController:alertController animated:YES completion:nil];
//        return;
//    }
//
    
    NSString *showTitle = [NSString stringWithFormat:@"您的预约额度为%.0f万提交后您的业务员将在一个工作日与您联系", self.viewModel.model.investmentMoney / 10000.0];
    

    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:showTitle preferredStyle:UIAlertControllerStyleAlert];
    
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [WHProgressHUD showStatus:@"预约中"];
        weakSelf.buyButton.userInteractionEnabled = NO;
        [weakSelf.buyButton setTitle:@"预约中" forState:UIControlStateNormal];
        [[weakSelf.viewModel.buyCommand execute:@(self.viewModel.model.investmentMoney / 10000)] subscribeNext:^(id  _Nullable x) {
            if ([x integerValue] == 1) {
                // 预约失败
                weakSelf.buyButton.userInteractionEnabled = YES;
                [weakSelf.buyButton setTitle:@"预约购买" forState:UIControlStateNormal];
                return;
            }
            
            [PXAlertView showAlertWithTitle:@"您已成功预约" message:@"您的专属理财师将会在一个工作日联系您" cancelTitle:@"知道了" completion:^(BOOL cancelled) {
                [weakSelf appointmentStatus:YES];
            }];
            
        }];

    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertController addAction:okAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
    
    
    
        
}

- (void)appointmentStatus:(BOOL)status
{
    if (status == YES) {
        _buyButton.backgroundColor = [UIColor lightGrayColor];
        [_buyButton setTitle:@"已预约" forState:UIControlStateNormal];
        _buyButton.userInteractionEnabled = NO;
    } else {
        _buyButton.backgroundColor = YLMainColor;
        [_buyButton setTitle:@"预约购买" forState:UIControlStateNormal];
        _buyButton.userInteractionEnabled = YES;
        
        
        if (self.viewModel.model.indexLimit <= 0) {
            _buyButton.backgroundColor = [UIColor lightGrayColor];
            [_buyButton setTitle:@"已售罄" forState:UIControlStateNormal];
            _buyButton.userInteractionEnabled = NO;
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY < 0) {
        _header.offsetY = offsetY;
        self.navigationController.navigationBar.subviews.firstObject.alpha = 0;
    } else {
        self.navigationController.navigationBar.subviews.firstObject.alpha =  offsetY * 1.5 / (_header.frame.size.height);
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 4) {
        return 3;
    }
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    if (indexPath.section == 0) {
        YLProductAmount0fMoneyCell *cell = [tableView dequeueReusableCellWithIdentifier:[YLProductAmount0fMoneyCell cellID]];
        cell.model = self.viewModel.model;
        return cell;
    } else if (indexPath.section == 1) {
        YLProductInvestmentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[YLProductInvestmentTableViewCell cellID]];
        cell.model = self.viewModel.model;
        return cell;
    } else if (indexPath.section == 2) {
        YLSubTitleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[YLSubTitleTableViewCell cellID]];
        cell.model = self.viewModel.model;
        return cell;
    } else if (indexPath.section == 3) {
        YLProductBuyingCycleCell *cell = [tableView dequeueReusableCellWithIdentifier:[YLProductBuyingCycleCell cellID]];
        cell.month = self.viewModel.model.productTerm;
        return cell;
    } else if (indexPath.section == 4) {
        YLIconTitleModel *model = self.viewModel.items[indexPath.row];
        YLTitleArrowNoSubCell *cell = [tableView dequeueReusableCellWithIdentifier:[YLTitleArrowNoSubCell cellID]];
        cell.iconTitleModel = model;
        return cell;
    }
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] init];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return YLScreenW * 148 / 747.0;
    } else if (indexPath.section == 1) {
        return YLScreenW * 226 / 749.0;
    } else if (indexPath.section == 2) {
        return YLScreenW * 97 / 747.0;
    } else if (indexPath.section == 3) {
        return YLScreenW * 219 / 750.0;
    } else if (indexPath.section == 4) {
        return 50;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return YLScreenW / 746.0 * 18;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 2) {
        __weak typeof(self) weakSelf = self;
        YLAccount *account = [YLAccountTool account];
        if (account.authState == 0) {
            YLCertifiedPaymentViewController *con = [[YLCertifiedPaymentViewController alloc] init];
            [weakSelf.navigationController pushViewController:con animated:YES];
            return ;
        } else {
            if (!self.viewModel.model) {
                return;
            }
            
            if (self.viewModel.model.customerProductVouchers.count == 0) {
                return;
            }
            
            YLInvestmentUsefulController *userful = [[YLInvestmentUsefulController alloc] init];
           
            userful.models = self.viewModel.model.customerProductVouchers;
            [self.navigationController pushViewController:userful animated:YES];
        }
    } else if (indexPath.section == 4) {
        
        YLIconTitleModel *model = self.viewModel.items[indexPath.row];
        if (model.clickBlock) {
            model.clickBlock();
        }
        
    }
}

- (void)dealloc
{
    NSLog(@"销毁");
}

@end
